package afters

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/httplib"
	"github.com/astaxie/beego/logs"
	"smart_home/api/models"
	"smart_home/api/xfyun/depots"
	"strings"
	"time"
)

func init() {
	registerAfter("timing_switch", timing_switch)
}

func timing_switch(intent *depots.Intent, result *depots.Result) {
	logs.Debug("timing_switch--->%+v", intent.Data)
	var (
		timeSlot *depots.Slot
		tts      *depots.TimeSlot
		hr       *httplib.BeegoHTTPRequest
		tms      []string
		tm       string
		url      = "http://api.rcenet.com/v2/timing"
		st       = beego.AppConfig.String("st")
		uid      = intent.Data.Result[0].Data["uid"].(string)
		sta      = intent.Data.Result[0].Data["sta"].(string)
		act      = intent.Data.Result[0].Data["act"].(bool)
		name     = intent.Data.Result[0].Data["name"].(string)
		actMsg   string
		ch       chan string
	)

	timeSlot = intent.GetSlot("time")
	if timeSlot == nil {
		logs.Error("time为空")
		return
	}

	if tts = intent.ToTimeSlot(timeSlot.NormValue); tts == nil {
		logs.Error("时间错误")
		return
	}

	tms = strings.Split(tts.Datetime, ":")
	tm = strings.Replace(strings.Join(tms[0:2], ":"), "T", "", 1)
	hr = httplib.Post(url).Header("st", st).Header("suid", uid).Param("sta", sta).Param("wkocc", "0000000").Param("loop", "0")
	if act {
		hr = hr.Param("start", tm)
		actMsg = "打开"
	} else {
		hr = hr.Param("end", tm)
		actMsg = "关闭"
	}

	ch = make(chan string)
	// 2.8秒过期
	after := time.After(500 * time.Millisecond)

	go func(ch chan string, hr *httplib.BeegoHTTPRequest, timeSlot *depots.Slot, actMsg, name string) {

		var (
			err    error
			resMsg = &models.ResultMsg{}
		)
		if err = hr.ToJSON(resMsg); err != nil {
			ch <- err.Error()
			return
		}
		if resMsg.Code == 0 {
			ch <- resMsg.Msg
		} else {
			ch <- fmt.Sprintf("正在为您设置%s定时%s%s", timeSlot.Value, actMsg, name)
		}
	}(ch, hr, timeSlot, actMsg, name)

	select {
	case d := <-ch:
		result.Answer.Text = d
		return
	case <-after:
		return
	}
}
